<template>
  <el-dialog v-model="dialogVisible" title="添加试卷" width="80%">
    <!-- 筛选表单 -->
    <el-form :inline="true" class="filter-form">
      <el-form-item label="学科">
        <el-select v-model="filterForm.subjectId" style="width: 200px" clearable placeholder="请选择学科">
          <el-option v-for="subject in subjectListData" :key="subject.id" :label="subject.name" :value="subject.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 试卷表格 -->
    <el-table 
      :data="tableData" 
      border 
      style="width: 100%"
      height="400"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55">
        <template #header>
          <el-checkbox v-model="isAllSelected" @change="handleSelectAll"></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="ID" width="80" align="center"/>
      <el-table-column label="学科" width="120" align="center">
        <template #default="{row}">
          {{ getSubjectName(row.subjectId) }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="试卷名称" min-width="200" />
      <el-table-column prop="createTime" label="创建时间" width="180" align="center" />
    </el-table>

    <!-- 分页控件 -->
    <div style="margin-top: 20px; display: flex; justify-content: center;">
      <el-pagination 
          background 
          layout="prev, pager, next" 
          :total="total" 
          :page-size="filterForm.pageSize"
          :current-page="filterForm.pageIndex"
          @current-change="handleCurrentChange" />
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSave">添加选中试卷</el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useLevelStore } from '@/stores/level';
import { type PaperItem, subjectList, type Subject, paperPage } from '@/api/renwu';

const LevelStore = useLevelStore();

// 删除冗余的formInline对象
// 只使用filterForm统一管理分页和筛选参数

// 筛选表单（包含分页参数）
const filterForm = reactive({
  gradeLevel: null as number | null,
  subjectId: null as number | null,
  pageIndex: 1,
  pageSize: 10
});

// 学科列表数据
const subjectListData = ref<Subject[]>([]);

// 试卷表格数据
const tableData = ref<PaperItem[]>([]);
const total = ref(0);

// 存储选中的行
const selectedRows = ref<PaperItem[]>([]);
// 全选状态
const isAllSelected = ref(false);

// 获取学科列表
const fetchSubjectList = async () => {
  try {
    const res = await subjectList();
    if (res.code === 1 && res.response) {
      subjectListData.value = res.response;
    } else {
      ElMessage.error(res.message || '获取学科列表失败');
    }
  } catch (error) {
    console.error('获取学科列表时出错:', error);
    ElMessage.error('获取学科列表失败，请稍后重试');
  }
};

// 根据学科ID获取学科名称
const getSubjectName = (subjectId: number): string => {
  const subject = subjectListData.value.find(s => s.id === subjectId);
  return subject ? subject.name : `学科${subjectId}`;
};

// 获取试卷列表
const getPaperList = () => {
  paperPage({
    gradeLevel: filterForm.gradeLevel,
    subjectId: filterForm.subjectId,
    pageIndex: filterForm.pageIndex,
    pageSize: filterForm.pageSize
  }).then(res => {
    if (res.code === 1 && res.response) {
      tableData.value = res.response.list;
      total.value = res.response.total;
      // 重置全选状态
      isAllSelected.value = false;
    } else {
      ElMessage.error(res.message || '获取试卷数据失败');
    }
  }).catch(error => {
    ElMessage.error('请求失败: ' + error.message);
  });
};

// 查询
const onSubmit = () => {
  filterForm.pageIndex = 1; // 重置为第一页
  getPaperList();
};

// 重置筛选条件
const resetFilter = () => {
  filterForm.gradeLevel = null;
  filterForm.subjectId = null;
  filterForm.pageIndex = 1; // 重置页码
  getPaperList();
};

// 分页处理
const handleCurrentChange = (val: number) => {
  filterForm.pageIndex = val; // 更新当前页码
  getPaperList();
};

// 控制对话框的显示与隐藏
const dialogVisible = ref(false);

// 定义可以触发的事件
const emit = defineEmits(['addPaper']);

// 提供一个方法用于打开对话框
const openDialog = () => {
  // 重置筛选条件
  resetFilter();
  // 清空选中项
  selectedRows.value = [];
  isAllSelected.value = false;
  
  dialogVisible.value = true;
};

// 处理行选择变化
const handleSelectionChange = (val: PaperItem[]) => {
  selectedRows.value = val;
  isAllSelected.value = val.length === tableData.value.length;
};

// 处理全选
const handleSelectAll = (val: boolean) => {
  if (val) {
    selectedRows.value = [...tableData.value];
  } else {
    selectedRows.value = [];
  }
  isAllSelected.value = val;
};

// 保存按钮点击事件处理函数
const handleSave = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一份试卷');
    return;
  }
  
  // 触发添加试卷事件
  emit('addPaper', selectedRows.value);
  
  // 显示成功消息
  ElMessage.success(`成功添加 ${selectedRows.value.length} 份试卷`);
  
  // 关闭对话框
  dialogVisible.value = false;
};

// 取消按钮点击事件处理函数
const handleCancel = () => {
  // 清空选中的数据
  selectedRows.value = [];
  // 关闭对话框
  dialogVisible.value = false;
};

onMounted(() => {
  fetchSubjectList();
});

defineExpose({
  openDialog
});
</script>

<style scoped>
/* 确保对话框内容可见 */
:deep(.el-dialog__body) {
  padding: 20px 25px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 15px;
}

.filter-form .el-form-item {
  margin-right: 15px;
  margin-bottom: 10px;
}

.el-table {
  margin-top: 15px;
  border-radius: 4px;
  overflow: hidden;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-tag {
  font-weight: bold;
}

/* 激活页码的样式 */
:deep(.el-pagination.is-background .el-pager li.active) {
  background-color: #409eff; /* 激活页码的背景颜色 */
  color: #fff; /* 激活页码的文字颜色 */
}

/* 鼠标悬停在页码上的样式 */
:deep(.el-pagination.is-background .el-pager li:not(.disabled):hover) {
  color: #409eff; /* 悬停时的文字颜色 */
}
</style>